using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace Voodoo.Sauce.Internal.Analytics
{
	internal class AdSessionQueue
	{
		private const string FIRST_AD_SESSIONS_KEY = "first_ad_sessions_key";

		private readonly List<AdSession> _firstSessionsList;

		private readonly Queue<AdSession> _latestSessionsQueue;

		private readonly object _syncRoot = new object();

		public AdSessionQueue()
		{
			try
			{
				_latestSessionsQueue = new Queue<AdSession>();
				string @string = NintendoPlayerPrefs.GetString("first_ad_sessions_key");
				_firstSessionsList = (string.IsNullOrEmpty(@string) ? new List<AdSession>() : JsonConvert.DeserializeObject<List<AdSession>>(@string));
			}
			catch (Exception)
			{
				_firstSessionsList = new List<AdSession>();
			}
		}

		internal List<Dictionary<string, object>> FirstSessionsDictionaryList()
		{
			return ToDictionaryList(_firstSessionsList);
		}

		internal List<Dictionary<string, object>> LatestSessionsDictionaryList()
		{
			return ToDictionaryList(_latestSessionsQueue);
		}

		private List<Dictionary<string, object>> ToDictionaryList(IEnumerable<AdSession> sessions)
		{
			List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
			lock (_syncRoot)
			{
				foreach (AdSession session in sessions)
				{
					list.Add(session.ToDictionary());
				}
				return list;
			}
		}

		internal void UpdateAdSessions(string Placement, AdClosedEventAnalyticsInfo adAnalyticsInfo, double? revenue, bool isClicked, bool isSkipped)
		{
			AdSession adSession = new AdSession
			{
				Placement = Placement,
				AdNetwork = adAnalyticsInfo.AdNetworkName,
				Cpm = revenue,
				CreativeId = adAnalyticsInfo.Creative,
				Duration = adAnalyticsInfo.AdDuration / 1000,
				IsClicked = isClicked,
				IsSkipped = isSkipped
			};
			lock (_syncRoot)
			{
				UpdateLatestAdSessions(adSession);
				UpdateFirstAdSessions(adSession);
			}
		}

		private void UpdateLatestAdSessions(AdSession adSession)
		{
			try
			{
				if (_latestSessionsQueue.Count == 20)
				{
					_latestSessionsQueue.Dequeue();
				}
				_latestSessionsQueue.Enqueue(adSession);
			}
			catch (Exception)
			{
			}
		}

		private void UpdateFirstAdSessions(AdSession adSession)
		{
			try
			{
				if (_firstSessionsList.Count != 20)
				{
					_firstSessionsList.Add(adSession);
					NintendoPlayerPrefs.SetString("first_ad_sessions_key", JsonConvert.SerializeObject(_firstSessionsList));
				}
			}
			catch (Exception)
			{
			}
		}
	}
}
